const tabLists=[
  '全部','月票榜','推荐榜','新书榜','完本榜','人气榜','打赏榜','土豪榜','分享榜','勤奋帮'
]
const charts=[
  '月票榜','推荐榜','新书榜','完本榜','打赏榜','土豪榜','分享榜','勤奋帮'
]
const apis=[
  'https://www.hotread.com/api/common/rank/6164/3/10?cb=175698432241',
  'https://www.hotread.com/api/common/rank/6163/3/10?cb=175698432244',
  'https://www.hotread.com/api/common/rank/6165/1/10?cb=175698432246',
  'https://www.hotread.com/api/common/rank/6170/2/10?cb=175698432249',
  'https://www.hotread.com/api/common/rank/6168/3/10?cb=175698432251',
  'https://www.hotread.com/api/common/rank/6166/2/10?cb=175698432254',
  'https://www.hotread.com/api/common/rank/6172/3/10?cb=175698432257',
  'https://www.hotread.com/api/common/rank/6171/0/10?cb=175699945001'
]
const tabsApis=[
  'https://www.hotread.com/api/common/rank/6164/3/20?pageNo=1&cb=1757133551116',
  'https://www.hotread.com/api/common/rank/6163/2/20?pageNo=1&cb=1757134722507',
  'https://www.hotread.com/api/common/rank/6165/1/20?pageNo=1&cb=1757134747818',
  'https://www.hotread.com/api/common/rank/6170/2/20?pageNo=1&cb=1757134780973',
  'https://www.hotread.com/api/common/rank/6161/2/20?pageNo=1&cb=1757135977308',
  'https://www.hotread.com/api/common/rank/6168/2/20?pageNo=1&cb=1757135988877',
  'https://www.hotread.com/api/common/rank/6166/2/20?pageNo=1&cb=1757136008437',
  'https://www.hotread.com/api/common/rank/6172/2/20?pageNo=1&cb=1757136020611',
  'https://www.hotread.com/api/common/rank/6171/0/20?pageNo=1&cb=1757136037076'
]

// 状态标记：记录当前激活的标签类型（全部/单个榜单）
let currentTabType = 'all'; 

// 初始化"全部"榜单的DOM和数据（先于tab事件绑定）
const chartRect = document.querySelector('.chart-rect');
if (chartRect) {
  // 1. 创建所有榜单容器DOM
  charts.forEach((chart, i) => {
    chartRect.innerHTML += `
      <div class="box">
        <div class="ranking">
          <div class="ranktop">
            <div class="rank-title">${chart}</div>
            <div class="rank-more">
              <p class="rank-time timeon">日</p>
              <p class="rank-time">周</p>
              <p class="rank-time">月</p>
            </div>
          </div>
          <ul class="rank-bottom"></ul>
        </div>
      </div>
    `;
  });

  // 2. 加载"全部"榜单数据
  const rankBottoms = document.querySelectorAll('.rank-bottom');
  rankBottoms.forEach((container, index) => {
    fetch(apis[index])
      .then(res => res.json())
      .then(res1 => {
        renderRank(container, res1.list, index);
      })
      .catch(err => {
        console.error('全部榜单数据加载失败:', err);
      });
  });
}

// 渲染其他榜单
function loadTabData(apiIndex, tabName) {
  const contents = document.querySelector('.contents');
  if (!contents) return;

  // 清空并显示单个榜单区域
  contents.innerHTML = '';
  contents.style.display = 'block';
  contents.style.visibility = 'visible'; // 强制可见

  fetch(tabsApis[apiIndex])
    .then(res => res.json())
    .then(res1 => {
      contents.innerHTML = `
        <div class="chart-title">${tabName}</div>
        <ul class="chart-cont">
            <li class="list-title">
                <span class="numa">序号</span>
                <span class="typea">分类</span>
                <span class="bookNamea">小说名称</span>
                <span class="newChaptera">更新章节</span>
                <span class="authora">作者</span>
                <span class="timea">最新更新时间</span>
            </li>
        </ul>
      `;
      const chartConts = document.querySelector('.chart-cont');
      res1.list.forEach((item, index) => {
        chartConts.innerHTML += `
          <li class="boyhover" onclick='jumps(${JSON.stringify(item.story)})'>
              <span class="numa">${index + 1 < 10 ? '0' + (index + 1) : index + 1}</span>
              <span class="typea">${item.story.type}</span>
              <span class="bookNamea">${item.story.name}<i class="vip-logo"></i></span>
              <span class="newChaptera">${item.story.latestChapter}</span>
              <span class="authora">${item.story.author}</span>
              <span class="timea">${item.updateTime}</span>
          </li>
        `;
      });
    })
    .catch(err => {
      console.error('单个榜单数据加载失败:', err);
    });
}

// 时间转换函数
function formatTime(dateString) {
  const targetDate = new Date(dateString);
  const now = new Date();
  const diffInMs = now - targetDate;
  const hour = 1000 * 60 * 60;
  const day = hour * 24;
  if (diffInMs < day) {
    const hours = Math.floor(diffInMs / hour);
    return `${hours}小时前`;
  } else {
    const days = Math.floor(diffInMs / day);
    return `${days}天前`;
  } 
}

// 渲染单个排行榜列表
function renderRank(container, list, contIndex) {
  container.innerHTML = '';
  list.forEach((item, index) => {
    const isFirst = index === 0;
    let hotContent;
    if (contIndex === 1) { 
      hotContent = `${item.topValue}推荐票`;
    } else if (contIndex === 4 ){
      hotContent = `${item.topValue}火星币`;
    } else if (contIndex === 6 ) {
      hotContent = `${item.topValue}分享`;
    } else if (contIndex === 7 ) {
      hotContent = formatTime(`${item.updateTime}`);
    } else {
      hotContent = Number(item.topValue) > 10000 
        ? `${(Number(item.topValue)/10000).toFixed(1)}万人气` 
        : `${item.topValue}人气`;
    }
    if (contIndex == 5){
      const rankItem = `
        <li class="rank-cont ${isFirst ? 'oncl' : ''}">
          <div class="rectbg ${isFirst ? 'onrectbg' : ''}" href="" onclick='jumps(${JSON.stringify(item.story)})'>
              <p class="num2 ${isFirst ? 'onnum2' : ''}">0${index + 1}</p>
              <div class="rankdesc ${isFirst ? 'onrank-desc' : ''}">
                  <p class="title2 ${isFirst ? 'ontitle2' : ''}">${item.nickName}</p>
                  <p class="hot ${isFirst ? 'onfreehot' : ''}">${item.topValue}土豪值</p>
              </div>
              <img src="${item.facePic?'https://p2.duyao001.com/image/article/15bcc989e86a8b1deb2dcc7286b23e59_150x150.png':item.facePic}" alt="用户头像" class="nonpic ${isFirst ? 'ontxtpic' : ''}">
          </div>
        </li>
      `;
      container.innerHTML += rankItem;
    } else {
      const rankItem = `
        <li class="rank-cont ${isFirst ? 'oncl' : ''}" >
          <div class="rectbg ${isFirst ? 'onrectbg' : ''}" href="" onclick='jumps(${JSON.stringify(item.story)})'>
              <p class="num2 ${isFirst ? 'onnum2' : ''}">0${index + 1}</p>
              <div class="rankdesc ${isFirst ? 'onrank-desc' : ''}">
                  <p class="title2 ${isFirst ? 'ontitle2' : ''}">${item.story.name}</p>
                  <p class="aut ${isFirst ? 'onauthor2' : ''}">
                    <i>${item.story.type} |</i>${item.story.author}
                  </p>
                  <p class="hot ${isFirst ? 'onfreehot' : ''}">${hotContent}</p>
              </div>
              <img src="${item.story.cover}" alt="小说封面" class="nonpic ${isFirst ? 'ontxtpic' : ''}">
          </div>
        </li>
      `;
      container.innerHTML += rankItem;
    }
  });
  
  container.innerHTML += `
    <li class="list-more" onclick="jumpBook()">
      <p class="more-txt">查看更多</p>        
    </li> 
  `;
  
  initMouseEvents(container);
}

// 初始化单个容器的鼠标交互事件
function initMouseEvents(container) {
  const lists = container.querySelectorAll('.rank-cont');
  if (lists.length === 0) return;
  
  let btitem = lists[0]; // 默认高亮第一个元素
  
  // 清除高亮
  const clearLights = () => {
    lists.forEach(item => {
      item.classList.remove('oncl');
      const rectbg = item.querySelector('.rectbg');
      const num2 = item.querySelector('.num2');
      const rankdesc = item.querySelector('.rankdesc');
      const title2 = item.querySelector('.title2');
      const aut = item.querySelector('.aut');
      const hot = item.querySelector('.hot');
      const nonpic = item.querySelector('.nonpic');
      
      if (rectbg) rectbg.classList.remove('onrectbg');
      if (num2) num2.classList.remove('onnum2');
      if (rankdesc) rankdesc.classList.remove('onrank-desc');
      if (title2) title2.classList.remove('ontitle2');
      if (aut) aut.classList.remove('onauthor2');
      if (hot) hot.classList.remove('onfreehot');
      if (nonpic) nonpic.classList.remove('ontxtpic');
    });
  };
  
  // 设置高亮
  const highLights = (item) => {
    item.classList.add('oncl');
    const rectbg = item.querySelector('.rectbg');
    const num2 = item.querySelector('.num2');
    const rankdesc = item.querySelector('.rankdesc');
    const title2 = item.querySelector('.title2');
    const aut = item.querySelector('.aut');
    const hot = item.querySelector('.hot');
    const nonpic = item.querySelector('.nonpic');
    
    if (rectbg) rectbg.classList.add('onrectbg');
    if (num2) num2.classList.add('onnum2');
    if (rankdesc) rankdesc.classList.add('onrank-desc');
    if (title2) title2.classList.add('ontitle2');
    if (aut) aut.classList.add('onauthor2');
    if (hot) hot.classList.add('onfreehot');
    if (nonpic) nonpic.classList.add('ontxtpic');
  };
  
  // 绑定鼠标事件
  lists.forEach(item => {
    item.addEventListener('mouseenter', () => {
      btitem = item;
      clearLights();
      highLights(item);
    });
    
    item.addEventListener('mouseleave', () => {
      clearLights();
      if (btitem) highLights(btitem);
    });
  });
}

// 绑定tab切换事件（在"全部"榜单初始化之后执行）
const nayboys = document.querySelector('.nav-boy');
if (nayboys) {
  tabLists.forEach((tab, index) => {
    const li = document.createElement('li');
    li.className = `list ${index === 0 ? 'on' : ''}`;
    li.textContent = tab;
    nayboys.appendChild(li);

    li.addEventListener('click', () => {
      // 更新激活状态
      document.querySelectorAll('.list').forEach(item => item.classList.remove('on'));
      li.classList.add('on');

      const contents = document.querySelector('.contents');
      if (!contents || !chartRect) return;

      if (index === 0) {
        // 切换到"全部"榜单
        currentTabType = 'all';
        chartRect.style.display = 'flex';
        chartRect.style.visibility = 'visible'; // 强制可见
        contents.style.display = 'none';
        contents.style.visibility = 'hidden'; // 强制隐藏
        contents.innerHTML = ''; // 彻底清空内容
      } else if (index >= 1 && index <= 9) {
        // 切换到单个榜单
        currentTabType = 'single';
        const apiIndex = index - 1;
        chartRect.style.display = 'none';
        chartRect.style.visibility = 'hidden'; // 强制隐藏
        loadTabData(apiIndex, tab);
      }
    });
  });
}

// 跳转详情页
function jumps(hearf) {
  location.href=`./detail.html?${JSON.stringify(hearf)}`
}

// 查看更多（补充定义，避免未定义错误）
// function jumpBook() {
//   // 根据当前激活的榜单类型跳转
//   if (currentTabType === 'all') {
//     // 全部榜单的"查看更多"逻辑
//     console.log('跳转到全部榜单更多页');
//   } else {
//     // 单个榜单的"查看更多"逻辑
//     console.log('跳转到单个榜单更多页');
//   }
// }
    